import './index.scss';
import React, { Component } from 'react'
import services from 'services';
import classNames from 'classnames';
import PageLayout from 'layouts/Page';
import Steps from 'components/Steps';
import Button from 'components/Button';
import Container from 'components/Container';
import * as PREORDER from 'constants/preorder';
import Modal from 'components/Modal';
import { loadingOn } from 'components/Loading';
import moment from 'moment';
import qs from 'qs';
import { _ } from 'libs/tools';

@PageLayout({ classNames: 'page-preorder-payment-success', title: '', showCrmButton: true })
class Page extends Component {
  stepsData = {
    steps: [{}, {}, {}, {}],
  }

  constructor(props) {
    super(props);

    this.state = {
      isReorderModalVisible: false,
      isRefoundModalVisible: false
    };
  }

  componentDidMount() {
    //  默认关闭页面
    this.props.setHeader({
      onBack: () => {
        location.href = 'jzapp://close_web_page';
      }
    });
    
    const recordId = this.props.match.params.recordId;
    services.Preorder.getPreorderDetail(recordId).then(res => {
      let { data, code } = res.data;
      // let { data, code } = {
      //   "code": 0,
      //   "subCode": 0,
      //   "msg": "ok",
      //   "data": {
      //     "recordDetail": {
      //       "queueRecordId": 37,
      //       "queueName": "上海9价HPV",
      //       "cityName": "市辖区",
      //       "status": qs.parse(location.href.split('?')[1]).status >> 0 || 1,
      //       "lineIndex": 0,
      //       "preLineIndex": 0,
      //       "lineIndexPer": 0,
      //       "birthday": "2003-08-14",
      //       "name": "张新青",
      //       "totalAmount": 2999,
      //       "productName": "全康医疗中心HPV9价",
      //       "mobile": "13636529154",
      //       "idCardNo": "330802199308013224",
      //       "skuName": null,
      //       "submitTime": "2019-04-17 13:00:01",
      //       "prepayAmount": 1000,
      //       "prepayOrderNo": "PRE201904171300004673",
      //       "prepayTime": "2019-04-17 13:00:01",
      //       "postPayAmount": 1999,
      //       "postPayOrderNo": "",
      //       "postPayTime": "2019-04-17 13:00:01",
      //       "expireTime": "2019-04-19 13:15:01"
      //     }
      //   }
      // };

      if (code == 0) {
        const UNPAID_PREORDER_STATUS = 0;
      
        if (data.recordDetail.status == UNPAID_PREORDER_STATUS) {
          return this.props.history.push(`/preorder/payment-fail/${data.recordDetail.queueRecordId}`);
        }
        
        this.setState({
          detail: data.recordDetail
        });

        //  set page header
        this.props.setHeader({ title: this.currentStatus[data.recordDetail.status].header});

        //  counter
        let { status, expireTime } = data.recordDetail;

        if (status === PREORDER.UNPAID) {
          const fixZero = n => n >= 10 ? n : '0' + n;

          const countDown = () => {
            let dom = document.querySelector('.expire-counter');
            if (!dom) return;
            let diff = moment(expireTime).toDate().getTime() - (new Date().getTime());
            let duration = moment.duration(diff, 'milliseconds');

            if (diff < 0) {
              //  jump step to expired
              this.setState({
                detail: {
                  ...this.state.detail,
                  status: PREORDER.EXPIRED
                }
              });
              this.props.setHeader({ title: '购苗失败'});
            }
            else {
              dom.innerHTML = fixZero(duration.hours()) + ":" + fixZero(duration.minutes()) + ":" + fixZero(duration.seconds());
            }
          }

          countDown();
          this.timer = setInterval(countDown, 1000);
        }
      }

      //  do some action
      let action = qs.parse(location.href.split('?')[1]).action;

      switch (action) {
        case 'refund':
          this.toggleRefoundModalVisible();
          break;
        case 'reorder':
          this.toggleReorderModalVisible();
          break;
        default:;
      }
    });
  }

  componentWillUnmount() {
    this.timer && clearInterval(this.timer);
  }

  toggleReorderModalVisible = (visible) => {
    this.setState({ isReorderModalVisible: visible !== undefined ? visible : !this.state.isReorderModalVisible });
  }

  toggleRefoundModalVisible = (visible) => {
    this.setState({ isRefoundModalVisible: visible !== undefined ? visible : !this.state.isRefoundModalVisible });
  }

  currentStatus = {
    [PREORDER.IN_QUEUE]: {
      header: '排队详情',
      titleIcon: 'in-queue',
      title: '您已成功进入队列',
      content: <span>到苗后我们会第一时间手机短信和APP通知您支付尾款<br/>届时请在收到通知后的2小时内支付尾款，确保购苗成功</span>,
      currentIndex: 1
    },
    [PREORDER.UNPAID]: {
      header: '待支付尾款',
      titleIcon: 'unpaid',
      title: '恭喜您排到疫苗了',
      content: <span>请及时支付尾款，确保您购苗成功<br/>剩余有效支付时间：<span className="expire-counter"></span></span>,
      currentIndex: 2
    },
    [PREORDER.PAID]: {
      header: '排队结果',
      titleIcon: 'paid',
      title: '恭喜购苗成功，不用再排队啦',
      content: <span>客服将在1到2天内，通过聊天功能与您预约接种时间<br/>请注意APP内的消息通知</span>,
      currentIndex: 3
    },
    [PREORDER.EXPIRED]: {
      header: '排队结果',
      titleIcon: 'fail',
      title: '购苗失败',
      content: <span>因为没有及时支付尾款购苗失败<br/>您可重新排队，再次加入疫苗队列或退款</span>,
      currentIndex: 3,
      reason: '支付超时'
    },
    [PREORDER.REFUND]: {
      header: '排队结果',
      titleIcon: 'fail',
      title: '购苗失败',
      content: <span>您已申请退款，排队定金将在半小时内退到微信账户</span>,
      currentIndex: 3,
      reason: '已申请退款'
    }
  }

  pay = () => {
    location.href = `jzapp://wechat_payment?orderId=${this.state.detail.postPayOrderNo}&recordId=${this.state.detail.queueRecordId}&orderType=postorder`;
  }

  refund = () => {
    loadingOn();

    services.Preorder.refund({ queueRecordId: this.state.detail.queueRecordId  }).then(res => {
      let { code, msg } = res.data;
      if (code != 0) return alert(msg);
      this.refreshPage();
    });
  }

  resetPreorder = () => {
    loadingOn();

    services.Preorder.resetPreorder({ recordId: this.state.detail.queueRecordId  }).then(res => {
      let { code, msg } = res.data;
      if (code != 0) return alert(msg);
      this.refreshPage();
    });
  }

  refreshPage = () => {
    let url = location.href.split('?');
    let path = url[0];
    let query = url[1] || '';

    //  remove some 1 time query
    if (query) {
      query = qs.parse(query);
      delete query['pay-success'];
      delete query['action'];
      query = qs.stringify(query);
    }

    location.href = path + '?' + query;
  }

  render() {
    let {
      isReorderModalVisible,
      isRefoundModalVisible,
      detail
    } = this.state;

    if (!detail) return null;
    
    let currentStatus = this.currentStatus[detail.status];

    return (
      <React.Fragment>
        { [PREORDER.EXPIRED, PREORDER.REFUND].includes(detail.status)  && <div className="tips-for-preorder">想重新排队，可联系右上角客服</div>}
        <Steps {...this.stepsData} currentIndex={currentStatus.currentIndex} cantBack />

        <div className="order-status">
          <h2>
            <span className={classNames(
              'icon', 
              `icon-${currentStatus.titleIcon}`
            )}></span>
            { currentStatus.title }
          </h2>
          <p>{currentStatus.content}</p>
        </div>

        <Container>
            <div className="card rank-info-card">
              <div className="card-hd">
                <h3>{detail.queueName}</h3>
              </div>
              <div className="card-bd">
                <ul className="list list-small">
                  {
                    [PREORDER.UNPAID, PREORDER.PAID].includes(detail.status) &&
                    <li>
                      <div className="key">疫苗总价：¥{detail.totalAmount}</div>
                    </li>
                  }
                  {
                    <li>
                      <div className="key">首付金额：¥{detail.prepayAmount}</div>
                      <div className="value">{[PREORDER.REFUND].includes(detail.status) ? '已退款' : '已付'}</div>
                    </li>
                  }
                  {
                    [PREORDER.UNPAID, PREORDER.PAID, PREORDER.EXPIRED].includes(detail.status) &&
                    <li>
                      <div className="key">尾款金额：¥{detail.postPayAmount}</div>
                      <div className="value">{[PREORDER.UNPAID, PREORDER.EXPIRED].includes(detail.status) ? <span className="danger">未付</span> : '已付'}</div>
                    </li>
                  }
                  <li>
                    <div className="key">排队时间：{detail.submitTime}</div>
                  </li>
                  {
                    ![PREORDER.IN_QUEUE, PREORDER.REFUND].includes(detail.status) &&
                    <li className="list-item-expand">
                      <div className="key">接种机构及疫苗：</div>
                      <div className="value">{detail.productName}</div>
                    </li>
                  }
                  {
                    [PREORDER.EXPIRED, PREORDER.REFUND].includes(detail.status) &&
                    <li>
                      <div className="key">失败原因：{currentStatus.reason}</div>
                    </li>
                  }
                </ul>
                {
                  ![PREORDER.REFUND].includes(detail.status) &&
                  <div className="rank">
                    <strong>{ PREORDER.PAID === detail.status ? detail.preLineIndex : detail.lineIndex }</strong>
                    <p>{ PREORDER.EXPIRED === detail.status ? '失效时排名' : (PREORDER.PAID === detail.status ? '已付款排名' : '当前排名') }</p>
                  </div>
                }
              </div>
            </div>

            <div className="card">
              <div className="card-hd">
                <h3>接种人信息</h3>
              </div>
              <ul className="list list-small">
                <li>
                  <div className="key">接种人姓名：</div>
                  <div className="value">{detail.name}</div>
                </li>
                <li>
                  <div className="key">接种人生日：</div>
                  <div className="value">{detail.birthday}</div>
                </li>
                <li>
                  <div className="key">身份证号：</div>
                  <div className="value">{detail.idCardNo}</div>
                </li>
                <li>
                  <div className="key">手机号：</div>
                  <div className="value">{detail.mobile}</div>
                </li>
              </ul>
            </div>

            {
              [PREORDER.IN_QUEUE, PREORDER.UNPAID].includes(detail.status) &&
              <div className="refund-tips" onClick={this.toggleRefoundModalVisible.bind(this, true)}>打退堂鼓了？点这里</div>
            }

            {
              [PREORDER.EXPIRED].includes(detail.status) &&
              <div className="operators">
                <div className="operator" onClick={this.toggleRefoundModalVisible.bind(this, true)}>申请退款</div>
                <div className="operator" onClick={this.toggleReorderModalVisible.bind(this, true)}>恢复排名，继续排队</div>
              </div>
            }

          {
            [PREORDER.UNPAID].includes(detail.status) &&
            <Button type={`block primary`} fixed onClick={this.pay}>¥{detail.postPayAmount} 去付尾款</Button>
          }

          {
            [PREORDER.PAID].includes(detail.status) &&
            <div className="card contact-crm-card">
              <div className="btn-contact-crm" onClick={_.throttle(() => {
                location.href = 'jzapp://message_company';
              }, 1500)}></div>
            </div>  
          }
          
        </Container>

        <Modal
          title="温馨提示"
          visible={isReorderModalVisible}
          footer={
            <React.Fragment>
              <div className="modal-btn" onClick={this.toggleReorderModalVisible.bind(this, false)}>取消</div>
              <div className="modal-btn" onClick={() => {
                this.toggleReorderModalVisible(false);
                this.resetPreorder();
              }}>继续排队</div>
            </React.Fragment>
          }
        >
          <ul>
            <li>您的排队定金依然生效</li>
            <li>您排队失效时的排名是第{detail.lineIndex}名，重新排队排名依然保持前列</li>
            <li>再次收到到苗通知后请及时支付尾款</li>
          </ul>
        </Modal>

        <Modal
          title="退款提示"
          visible={isRefoundModalVisible}
          footer={
            <React.Fragment>
              <div className="modal-btn" onClick={this.toggleRefoundModalVisible.bind(this, false)}>取消</div>
              <div className="modal-btn" onClick={() => {
                this.toggleRefoundModalVisible(false);
                this.refund();
              }}>确认退款</div>
            </React.Fragment>
          }
        >
          <ul>
            <li>退款后当前排队将失效</li>
            <li>排队定金将在半小时内退到微信账户</li>
          </ul>
        </Modal>
      </React.Fragment>
    )
  }
}

export default Page;